// httpListener
// Http端口监听单元
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

const AccessTokenKey string = "zyp20190128"
const SecondOfDay int64 = 24 * 60 * 60 //一天的秒数

type HttpListener struct {
	cfg *Config
}

func ListenHttpService(cfg *Config) {
	listenter := HttpListener{}
	listenter.cfg = cfg
	listenter.listen(cfg.HttpsPort)
}

func (p *HttpListener) listen(port int) {
	sPort := ""
	var err error
	//测试接口
	http.HandleFunc("/test", p.testInterface)
	// 定位GPS
	http.HandleFunc("/gps", p.smartTireGps)
	// 胎温胎压
	http.HandleFunc("/tiredata", p.smartTireTireData)

	//开始监听
	go func() {
		sPort = fmt.Sprintf(":%d", p.cfg.HttpsPort)
		zLog("开始监听端口:", sPort, " HTTPS:", p.cfg.HTTPS)
		if p.cfg.HTTPS {
			err = http.ListenAndServeTLS(sPort, p.cfg.CertFile, p.cfg.KeyFile, nil)
		} else {
			err = http.ListenAndServe(sPort, nil)
		}
		if err != nil {
			zLogError("监听端口:", sPort, "失败:", err)
		}
	}()

}

// 测试接口
func (p *HttpListener) testInterface(w http.ResponseWriter, req *http.Request) {
	zLog(req.RemoteAddr, "连接成功")
	// 请求方式：GET POST DELETE PUT UPDATE
	zLog("method:", req.Method)

	s := `{"code":000000}`
	w.Write([]byte(s))
}

type GPSDataSendT struct {
	SN            string  `json:"SN"`
	Type          int     `json:"Type"`
	DeviceUTCTime string  `json:"DeviceUTCTime"`
	Latitude      float64 `json:"Latitude"`
	Longitude     float64 `json:"Longitude"`
	Speed         float64 `json:"Speed"`
	Course        int     `json:"Course"`
	DeviceBattery float64 `json:"DeviceBattery"`
	PowerSource   int     `json:"PowerSource"`
	Flag          string  `json:"flag"`
}

// 定位GPS
func (p *HttpListener) smartTireGps(w http.ResponseWriter, req *http.Request) {
	zLog("smartTireGps req.Body:", req.Body)
	gpsSend := GPSDataSendT{}
	err := json.NewDecoder(req.Body).Decode(&gpsSend)
	if err != nil {
		zLogError("smartTireGps req.Body error::", err.Error())
	}
	zLog(fmt.Sprintf("smartTireGps gpsSend::%v", gpsSend))
	zLog(fmt.Sprintf("smartTireGps gpsSend.Flag::%s", gpsSend.Flag))

	// 返回值
	ret := make(map[string]interface{})
	ret["code"] = 0
	ret["msg"] = "success"
	ret["data"] = gpsSend

	// 如果你想将结果返回给客户端，你可以使用以下代码
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(ret)
	return
}

type TireDataSendT struct {
	SN            string  `json:"SN"`
	Type          int     `json:"Type"`
	SensorID      string  `json:"SensorID"`
	DeviceUTCTime string  `json:"DeviceUTCTime"`
	Latitude      float32 `json:"Latitude"`
	Longitude     float32 `json:"Longitude"`
	TirePressure  float32 `json:"TirePressure"`
	Temperature   int     `json:"Temperature"`
	SensorBattery float32 `json:"SensorBattery"`
	WheelPlace    string  `json:"WheelPlace"`
	TireStatus    string  `json:"TireStatus"`
	Flag          string  `json:"flag"`
}

// 胎温胎压
func (p *HttpListener) smartTireTireData(w http.ResponseWriter, req *http.Request) {
	zLog("smartTireTireData req.Body:", req.Body)
	tireSend := TireDataSendT{}
	err := json.NewDecoder(req.Body).Decode(&tireSend)
	if err != nil {
		zLogError("smartTireTireData req.Body error::", err.Error())
	}
	zLog(fmt.Sprintf("smartTireTireData tireSend::%v", tireSend))
	zLog(fmt.Sprintf("smartTireGps tireSend.Flag::%s", tireSend.Flag))

	// 返回值
	ret := make(map[string]interface{})
	ret["code"] = 0
	ret["msg"] = "success"
	ret["data"] = tireSend

	// 如果你想将结果返回给客户端，你可以使用以下代码
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(ret)
	return
}
